package linkwechat.serviceimp;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import linkwechat.mapper.system.SysDeptMapper;
import linkwechat.pojo.SysDept;
import linkwechat.sysservice.SysDeptService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

// 部门 业务层
@Service
public class SysDeptServiceImp extends ServiceImpl<SysDeptMapper,SysDept> implements SysDeptService {

    @Resource
    SysDeptMapper sysDeptMapper;

     //   查询所有部门
    @Override
    public List<SysDept> SelectDeptList() {
        List<SysDept> list = selectList();
        return list;
    }

//    根据部门名称或部门状态查询
    @Override
    public List<SysDept> SelectDeptLike(SysDept sysDept) {
        List<SysDept> list = sysDeptMapper.SelectDeptLike(sysDept);
        return list;
    }

    @Override
    public int AddDept(SysDept sysDept) {
        return sysDeptMapper.AddDept(sysDept);
    }


    @Override
    public int DeleteDept(Long deptId) {
        return sysDeptMapper.DeleteDept(deptId);
    }


    public List<SysDept> selectList() {
//        查询所有部门
        List<SysDept> listAll = sysDeptMapper.SelectDeptList();
        //根节点集合
        ArrayList<SysDept> arrayList = new ArrayList<>();
        for (SysDept sysDept : listAll) {
            if (sysDept.getParentId() == 0) {
                arrayList.add(sysDept);
            }
        }
        for (SysDept sysDept : arrayList) {
            /* 获取根节点下的所有子节点 使用getChild方法*/
            List<SysDept> childList = getChild(sysDept.getDeptId().toString(), listAll);
            sysDept.setChildren(childList);//给根节点设置子节点
        }
        return arrayList;
    }


//    获取根节点
    public List<SysDept> getChild(String id,List<SysDept> allList){
        //子菜单
        List<SysDept> childList = new ArrayList<>();
        for (SysDept sysDept : allList) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (sysDept.getParentId().toString().equals(id)) {
                childList.add(sysDept);
            }
        }
        //递归
        for (SysDept sysDept : childList) {
            sysDept.setChildren(getChild(sysDept.getDeptId().toString(), allList));
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

}
